#define _CRT_SECURE_NO_WARNINGS 1


class Solution {
public:
    int longestOnes(vector<int>& nums, int k)
    {
        int ans = 0;
        int left = 0, right = 0;
        int n = nums.size();
        int count = 0;
        while (right < n)
        {
            if (nums[right] != 1)
            {
                count++;
            }
            while (count > k)
            {
                if (nums[left++] == 0) count--;
            }
            ans = max(ans, right - left + 1);
            right++;
        }

        return ans;
    }
};


class Solution {
public:
    int minOperations(vector<int>& nums, int x)
    {
        int sum = 0;
        for (auto c : nums) sum += c;
        int n = nums.size();

        int left = 0, right = 0;

        int aim = sum - x;
        if (aim < 0) return -1;


        int ans = INT_MIN;
        sum = 0;
        while (right < n)
        {
            sum += nums[right];

            while (sum > aim)
            {
                sum -= nums[left++];
            }
            if (sum == aim) ans = max(ans, right - left + 1);
            right++;
        }

        return ans == INT_MIN ? -1 : n - ans;
    }
};



class Solution {
public:
    int totalFruit(vector<int>& fruits)
    {
        unordered_map<int, int> h;
        int left = 0, right = 0, ans = 0;
        int n = fruits.size();
        while (right < n)
        {
            h[fruits[right]]++;

            while (h.size() > 2)
            {
                h[fruits[left]]--;
                if (h[fruits[left]] == 0)
                {
                    h.erase(fruits[left]);
                }
                left++;
            }
            ans = max(ans, right - left + 1);
            right++;
        }

        return ans;
    }
};